from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.db.models import Q

from .models import Article
from core.models import SiteInfo, PageVisitCount

class ArticleListView(ListView):
    """文章列表视图"""
    model = Article
    template_name = 'articles/article_list.html'
    context_object_name = 'articles'
    paginate_by = 10
    
    def get_queryset(self):
        queryset = Article.objects.filter(is_published=True).select_related('author')
        
        # 搜索功能
        search_query = self.request.GET.get('q')
        if search_query:
            queryset = queryset.filter(
                Q(title__icontains=search_query) | 
                Q(content__icontains=search_query)
            )
        
        return queryset
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_info'] = SiteInfo.get_site_info()
        context['search_query'] = self.request.GET.get('q', '')
        
        # 为文章添加访问量
        articles_with_visits = list(context['articles'])
        article_ids = [article.id for article in articles_with_visits]
        article_visits = dict(
            PageVisitCount.objects.filter(
                content_type='article', 
                object_id__in=article_ids
            ).values_list('object_id', 'visit_count')
        )
        for article in articles_with_visits:
            article.visit_count = article_visits.get(article.id, 0)
            
        return context

class ArticleDetailView(DetailView):
    """文章详情视图"""
    model = Article
    template_name = 'articles/article_detail.html'
    context_object_name = 'article'
    
    def get_queryset(self):
        # 确保只有已发布的文章可见
        return Article.objects.filter(is_published=True).select_related('author')
    
    def get_object(self):
        """获取文章对象，并增加访问计数"""
        obj = super().get_object()
        # 记录文章访问量
        PageVisitCount.increment_count('article', obj.id, self.request.path)
        return obj
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['site_info'] = SiteInfo.get_site_info()
        
        # 获取相关文章（最新的3篇，排除当前文章）
        article = self.get_object()
        related_articles = Article.objects.filter(
            is_published=True
        ).exclude(id=article.id).order_by('-created_at')[:3]
        
        context['related_articles'] = related_articles
        return context
